package org.example.service;

import org.example.ioc.annotation.Service;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Service("countdownService")
public class CountdownService {

    private ScheduledExecutorService scheduledExecutorService;

    public CountdownService() {
        // 创建线程池
        this.scheduledExecutorService = Executors.newScheduledThreadPool(2);
    }

    public void startCountdown(int seconds) {
        System.out.println("开始 " + seconds + " 秒倒计时");
        
        AtomicInteger countdown = new AtomicInteger(seconds);

        scheduledExecutorService.scheduleAtFixedRate(() -> {
            int currentSeconds = countdown.get();
            if (currentSeconds > 0) {
                System.out.println("倒计时: " + currentSeconds + " 秒");
                countdown.decrementAndGet();
            } else {
                System.out.println("倒计时结束!");
                // 关闭线程池
                scheduledExecutorService.shutdown();
            }
        }, 0, 1, TimeUnit.SECONDS);
    }

    public void startClock() {
        System.out.println("启动时钟服务");

        scheduledExecutorService.scheduleAtFixedRate(() -> {
            System.out.println("当前时间: " + new java.util.Date());
        }, 0, 1, TimeUnit.SECONDS);
    }
}
